package com.micro.service.auth.server.config.oauth2;


import com.micro.service.auth.server.utils.AsyncThreadPool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.concurrent.TimeUnit;

/**
 * @author lvxiucai
 * @description 自定义刷新令牌授权
 * @date 2019/9/27
 */
@Slf4j
public class CustomRefreshTokenGranter extends RefreshTokenGranter {

    private AsyncThreadPool asyncThreadPool;


    public CustomRefreshTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
        super(tokenServices, clientDetailsService, requestFactory);
    }

    protected CustomRefreshTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, String grantType) {
        super(tokenServices, clientDetailsService, requestFactory, grantType);
    }


    @Override
    protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) {
        String refreshToken = tokenRequest.getRequestParameters().get("refresh_token");
        OAuth2AccessToken token = getTokenServices().refreshAccessToken(refreshToken, tokenRequest);

        if(token != null && !token.isExpired()){
            String userId =token.getAdditionalInformation().get("userId").toString();
            //token同步到老系统的redis


        }


        return token;
    }

    public AsyncThreadPool getAsyncThreadPool() {
        return asyncThreadPool;
    }

    public void setAsyncThreadPool(AsyncThreadPool asyncThreadPool) {
        this.asyncThreadPool = asyncThreadPool;
    }


}
